import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { handleWechatCallback } from '../../services/wechatLogin';
import { useAuth } from '../../hooks/useAuth';
import { type UserInfo, UserRole } from '../../types/auth';
import './WechatCallback.css';

function WechatCallback() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { login } = useAuth();
  const [status, setStatus] = useState<'processing' | 'success' | 'error'>('processing');
  const [message, setMessage] = useState('正在处理微信登录...');

  useEffect(() => {
    const processCallback = async () => {
      try {
        const code = searchParams.get('code');
        const state = searchParams.get('state');
        
        if (!code || !state) {
          setStatus('error');
          setMessage('登录参数无效');
          setTimeout(() => {
            navigate('/login');
          }, 3000);
          return;
        }

        // 处理微信回调
        const result = await handleWechatCallback(code, state);
        
        if (result.status === 'confirmed') {
          setStatus('success');
          setMessage('登录成功，正在跳转...');
          
          // 调用认证上下文的登录函数
          if (result.userInfo) {
            const userInfoForAuth: UserInfo = {
              id: result.userInfo.openid,
              openid: result.userInfo.openid,
              nickname: result.userInfo.nickname,
              headimgurl: result.userInfo.headimgurl,
              role: UserRole.USER, // 默认角色，实际应该从后端获取
              permissions: [], // 权限将在AuthContext中设置
              unionid: result.userInfo.unionid,
              accessToken: result.accessToken
            };
            
            login(userInfoForAuth);
          }
          
          setTimeout(() => {
            navigate('/');
          }, 2000);
        } else {
          setStatus('error');
          setMessage('登录失败，请重试');
          setTimeout(() => {
            navigate('/login');
          }, 3000);
        }
      } catch (error) {
        console.error('处理微信回调失败:', error);
        setStatus('error');
        setMessage('登录失败，请重试');
        setTimeout(() => {
          navigate('/login');
        }, 3000);
      }
    };

    processCallback();
  }, [searchParams, navigate, login]);

  return (
    <div className="wechat-callback">
      <div className="callback-container">
        <div className="callback-content">
          {status === 'processing' && (
            <>
              <div className="loading-spinner"></div>
              <h2>正在处理微信登录</h2>
              <p>{message}</p>
            </>
          )}
          
          {status === 'success' && (
            <>
              <div className="success-icon">✅</div>
              <h2>登录成功</h2>
              <p>{message}</p>
            </>
          )}
          
          {status === 'error' && (
            <>
              <div className="error-icon">❌</div>
              <h2>登录失败</h2>
              <p>{message}</p>
              <button 
                className="retry-btn"
                onClick={() => navigate('/login')}
              >
                返回登录页面
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

export default WechatCallback; 